#include <iostream>
#include <unistd.h>
#include <cstdlib>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;
void Write(int fd)
{
    char buffer[1024] = {0};
    pid_t id = getpid();
    int n = 0;
    string s = "I am child";
    while(1)
    {
        snprintf(buffer,sizeof(buffer),"%s-%d-%d",s.c_str(),id,n);
        n++;
        write(fd,buffer,sizeof(buffer));
        sleep(1);
        if(n == 5) break;
    }
}

void Read(int fd)
{
    char buffer[1024] = {0};
    while(1)
    {
        ssize_t s = read(fd,buffer,sizeof(buffer));
        if(s > 0)
        {
            cout << buffer << endl;
        }
        else if(s == 0)
        {
            cout << "read ending" << endl;
            break;
        }
        else{
            cout << "read fail" << endl;
        }
    }
}


int main()
{
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    if(n < 0) cout << "pipe file" << endl;
    pid_t id = fork();
    if(id < 0) return -1;
    if(id == 0)
    {
        //child
        close(pipefd[0]);
        Write(pipefd[1]);

        //close(pipefd[1]);
        exit(0);
    }
    //father
    close(pipefd[1]);
    Read(pipefd[0]);
    
    pid_t ret = waitpid(id,nullptr,0);
    if(ret==id) cout << "wait success" << endl;
    else cout << "wait fail" << endl;
    //close(pipefd[0]);
    return 0;
}